<template>
  <view>
    <cu-custom bgColor="bg-gradual-orange" :isBack="true">
      <template v-slot:content>{{ merchant.name }}</template>
    </cu-custom>

    <!-- 商家信息头部 -->
    <view class="header-card">
      <view class="flex align-center">
        <image class="cu-avatar round lg" :src="merchant.banner"></image>
        <view class="margin-left-sm flex-sub">
          <view class="text-bold text-lg">{{ merchant.name }}</view>
          <view class="text-sm text-gray margin-top-xs">
            <text class="text-orange">{{ merchant.rating }}分</text>
            <text class="margin-lr-xs">|</text>
            <text>月售{{ merchant.monthlySales }}+</text>
            <text class="margin-lr-xs">|</text>
            <text>配送约{{ merchant.distance }}</text>
          </view>
        </view>
        <button class="cu-btn round sm line-gray">
          <text class="cuIcon-favorfill text-yellow margin-right-xs"></text>
          收藏
        </button>
      </view>
      <view class="margin-top-sm">
        <scroll-view scroll-x>
          <view class="flex">
            <view
              class="cu-tag bg-red light sm round margin-right-xs"
              v-for="(discount, index) in merchant.tags"
              :key="index"
              >{{ discount }}</view
            >
          </view>
        </scroll-view>
      </view>
    </view>

    <!-- 固定Tab -->
    <scroll-view scroll-x class="bg-white nav text-center fixed-nav shadow-sm">
      <view
        class="cu-item"
        :class="activeTab === tab.value ? 'text-orange cur' : ''"
        v-for="(tab, index) in tabs"
        :key="index"
        @tap="activeTab = tab.value"
      >
        {{ tab.name }}
      </view>
    </scroll-view>

    <!-- 内容区域 -->
    <view class="content-container">
      <!-- 点餐 -->
      <view v-if="activeTab === 'order'" class="flex order-section">
        <scroll-view scroll-y class="nav-left">
          <view
            class="cu-item"
            :class="activeCategory === category.id ? 'cur' : ''"
            v-for="(category, index) in categories"
            :key="index"
            @tap="activeCategory = category.id"
          >
            {{ category.name }}
          </view>
        </scroll-view>
        <scroll-view scroll-y class="nav-right">
          <view class="cu-list">
            <view
              class="goods-item"
              v-for="(goods, index) in currentGoods"
              :key="index"
            >
              <image :src="goods.img" class="goods-img"></image>
              <view class="goods-content">
                <view class="text-bold">{{ goods.name }}</view>
                <view class="text-xs text-gray margin-top-xs"
                  >月售{{ goods.sales }}+</view
                >
                <view class="flex justify-between align-center margin-top-sm">
                  <text class="text-price text-red text-bold text-lg">{{
                    goods.price
                  }}</text>
                  <view class="stepper">
                    <button
                      class="cu-btn round sm icon"
                      @click="onMinus(goods)"
                      v-if="!goods.has_spec && getCartCount(goods.id) > 0"
                    >
                      <text class="cuIcon-move"></text>
                    </button>
                    <text
                      class="count"
                      v-if="!goods.has_spec && getCartCount(goods.id) > 0"
                      >{{ getCartCount(goods.id) }}</text
                    >
                    <button
                      class="cu-btn round sm"
                      :class="goods.has_spec ? 'bg-orange' : 'bg-yellow icon'"
                      @click="onPlus(goods)"
                    >
                      <text class="cuIcon-add" v-if="!goods.has_spec"></text>
                      <text v-else>选规格</text>
                    </button>
                  </view>
                </view>
              </view>
            </view>
          </view>
        </scroll-view>
      </view>

      <!-- 评价 -->
      <view v-if="activeTab === 'comment'" class="padding-sm">
        <view class="cu-card case" v-for="i in 3" :key="i">
          <view class="cu-item shadow">
            <view class="cu-list menu-avatar">
              <view class="cu-item">
                <view
                  class="cu-avatar round lg"
                  style="
                    background-image: url(https://via.placeholder.com/40x40);
                  "
                ></view>
                <view class="content">
                  <view>用户12345</view>
                  <view class="text-gray text-sm">
                    <text
                      class="cuIcon-starfill text-yellow"
                      v-for="star in 5"
                      :key="star"
                    ></text>
                  </view>
                </view>
              </view>
            </view>
            <view class="text-content padding-sm">
              这家店的耗儿鱼非常好吃，辣度适中，下次还会再来！
            </view>
            <view class="grid flex-sub padding-lr col-3 grid-square">
              <view
                class="bg-img"
                style="background-image: url(https://via.placeholder.com/80x80)"
                v-for="(item, index) in 3"
                :key="index"
              ></view>
            </view>
          </view>
        </view>
      </view>

      <!-- 商家 -->
      <view v-if="activeTab === 'merchant'" class="padding-sm">
        <view class="cu-list menu card-menu margin-top-sm">
          <view class="cu-item">
            <view class="content">
              <text class="cuIcon-info text-blue"></text>
              <text class="text-grey">商家详情</text>
            </view>
          </view>
          <view class="padding-sm bg-white">
            本店专注于提供优质的耗儿鱼菜品，采用新鲜食材，精心烹饪，为您带来美味体验。
          </view>
          <view class="cu-item">
            <view class="content">
              <text class="cuIcon-moneybag text-orange"></text>
              <text class="text-grey">起送价: {{ minOrder }}元</text>
            </view>
          </view>
          <view class="cu-item">
            <view class="content">
              <text class="cuIcon-deliver text-green"></text>
              <text class="text-grey">配送费: {{ deliveryFee }}元</text>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 底部结算栏 -->
    <view class="cu-bar bg-white tabbar shop-foot">
      <view class="action" @click="showCart = true">
        <view class="cu-avatar-group">
          <view class="cu-avatar round lg bg-red shadow">
            <text class="cuIcon-cart"></text>
            <view class="cu-tag badge" v-if="cartTotal > 0">{{
              cartTotal
            }}</view>
          </view>
        </view>
      </view>
      <view class="action text-lg text-bold text-red">
        ¥{{ cartDisplayPrice }}
      </view>
      <view
        class="bg-red submit"
        :class="cartTotal === 0 ? 'bg-gray' : 'bg-red'"
        @click="goToCheckout"
        >去结算</view
      >
    </view>

    <!-- 规格选择弹窗 -->
    <view
      class="cu-modal"
      :class="showSpecModal ? 'show' : ''"
      @tap="hideModal"
    >
      <view class="cu-dialog" @tap.stop>
        <view class="cu-bar bg-white justify-end">
          <view class="content">{{ currentSpecGoods.name }}</view>
          <view class="action" @tap="hideModal">
            <text class="cuIcon-close text-red"></text>
          </view>
        </view>
        <view class="padding-xl">
          <view
            class="spec-section"
            v-for="spec in currentSpecDetails"
            :key="spec.spe_id"
          >
            <view class="text-bold margin-bottom-sm">{{ spec.spe_type }}</view>
            <view>
              <view
                class="cu-tag round margin-right-sm margin-bottom-sm"
                :class="
                  selectedSpecs[spec.spe_id] === val.val_id
                    ? 'bg-orange'
                    : 'line-orange'
                "
                v-for="val in spec.values"
                :key="val.val_id"
                @click="selectSpec(spec.spe_id, val.val_id)"
              >
                {{ val.spe_val }}
              </view>
            </view>
          </view>
        </view>
        <view class="cu-bar bg-white">
          <view
            class="action margin-0 flex-sub text-green solid-left"
            @click="confirmAddToCart"
            >加入购物车</view
          >
        </view>
      </view>
    </view>

    <!-- 购物车详情弹窗 -->
    <shopping-cart
      :show="showCart"
      :cart="cart"
      :merchantId="merchant.id"
      @hide="showCart = false"
      @update:cart="handleUpdateCart"
      @update:totalPrice="handlePriceUpdate"
    />
  </view>
</template>

<script setup>
import { ref, computed, onMounted } from "vue";
import { get, post } from "@/utils/request.js";
import ShoppingCart from "@/components/ShoppingCart.vue";
import { onLoad, onUnload, onHide, onPageShow } from "@dcloudio/uni-app";

const merchant = ref({});
const deliveryFee = ref(0);
const packingFee = ref(0);
const goodsList = ref([]);
const activeTab = ref("order");
const activeCategory = ref("all");
const cart = ref({});
const showCart = ref(false);
const cartDisplayPrice = ref("0.00");
// 添加购物车变更标记
const cartHasChanged = ref(false);

// 规格弹窗相关状态
const showSpecModal = ref(false);
const currentSpecGoods = ref({});
const currentSpecDetails = ref([]);
const selectedSpecs = ref({});

// 规格转换函数
const convertSpecs = (specsObject) => {
  return Object.entries(specsObject).map(([speId, valId]) => ({
    spe_id: parseInt(speId),
    val_id: parseInt(valId),
  }));
};

// 选择规格
const selectSpec = (specId, valueId) => {
  selectedSpecs.value[specId] = valueId;
  console.log("当前规格选择:", selectedSpecs.value);
};

// 确认添加到购物车
const confirmAddToCart = async () => {
  // 验证是否选择了所有规格
  if (
    Object.keys(selectedSpecs.value).length < currentSpecDetails.value.length
  ) {
    uni.showToast({ title: "请选择完整的规格", icon: "none" });
    return;
  }

  // 转换规格数据为目标格式
  const selectedSpecsArray = convertSpecs(selectedSpecs.value);
  console.log("加入购物车的规格数据:", selectedSpecsArray);

  // 生成购物车项的唯一标识
  const specValues = Object.values(selectedSpecs.value).sort().join("_");
  const cartKey = `${currentSpecGoods.value.id}_${specValues}`;

  // 创建或更新购物车项
  const item = cart.value[cartKey] || {
    goods: {
      ...currentSpecGoods.value,
      specs: selectedSpecsArray, // 存储规格数组
    },
    selectedSpecs: selectedSpecsArray,
    quantity: 0,
    price: currentSpecGoods.value.price,
  };
  item.quantity++;
  cart.value[cartKey] = item;

  // 标记购物车已变更
  cartHasChanged.value = true;

  hideModal();

  // 调用套餐查询接口
  try {
    const res = await post("/combo/query", selectedSpecsArray);
    console.log("套餐查询结果:", res.data);
    // 将套餐信息附加到购物车项
    if (cart.value[cartKey]) {
      cart.value[cartKey].comboInfo = res.data;
      if (res.data && res.data.comPrice !== undefined) {
        cart.value[cartKey].price = res.data.comPrice;
      }
    }
  } catch (error) {
    console.error("套餐查询失败:", error);
    uni.showToast({ title: "获取套餐信息失败", icon: "none" });
  }
};

const onPlus = async (goods) => {
  if (goods.has_spec) {
    currentSpecGoods.value = goods;
    await fetchSpecifications(goods.id);
    showSpecModal.value = true;
  } else {
    const cartKey = goods.id;
    const item = cart.value[cartKey] || {
      goods,
      quantity: 0,
      price: goods.price,
    };
    item.quantity++;
    cart.value[cartKey] = item;
    // 标记购物车已变更
    cartHasChanged.value = true;
  }
};

const onMinus = (goods) => {
  const cartKey = goods.id;
  if (cart.value[cartKey]) {
    cart.value[cartKey].quantity--;
    if (cart.value[cartKey].quantity <= 0) {
      delete cart.value[cartKey];
    }
    // 标记购物车已变更
    cartHasChanged.value = true;
  }
};

const getCartCount = (goodsId) => {
  let count = 0;
  for (const key in cart.value) {
    if (key.startsWith(goodsId)) {
      count += cart.value[key].quantity;
    }
  }
  return count;
};

const cartTotal = computed(() => {
  return Object.values(cart.value).reduce(
    (sum, item) => sum + item.quantity,
    0
  );
});

const tabs = [
  { name: "点餐", value: "order" },
  { name: "评价", value: "comment" },
  { name: "商家", value: "merchant" },
];

const categories = ref([{ id: "all", name: "全部" }]);

const currentGoods = computed(() => {
  if (activeCategory.value === "all") {
    return goodsList.value;
  }
  return goodsList.value.filter((g) => g.typeId === activeCategory.value);
});

async function fetchSpecifications(goodId) {
  console.log(`正在为商品ID ${goodId} 获取规格...`);

  try {
    // 实际API调用
    const res = await get(`/goods/spec?goodId=${goodId}`);
    console.log("商品规格", res.data.msg);

    // 处理API返回的扁平化数据，转换为结构化格式
    if (res.data && res.data.msg && res.data.msg.length > 0) {
      // 按spe_id分组整理规格数据
      const specsMap = {};

      res.data.msg.forEach((item) => {
        // 如果这个规格类型还没被添加到map中
        if (!specsMap[item.spe_id]) {
          specsMap[item.spe_id] = {
            spe_id: item.spe_id,
            spe_type: item.spe_type,
            values: [],
          };
        }

        // 添加规格值到对应类型的values数组中
        specsMap[item.spe_id].values.push({
          val_id: item.val_id,
          spe_val: item.spe_val,
        });
      });

      // 转换为数组并赋值给currentSpecDetails
      currentSpecDetails.value = Object.values(specsMap);
    } else {
      // 如果没有规格数据，设置为空数组
      currentSpecDetails.value = [];
    }
  } catch (error) {
    console.error("获取规格失败:", error);
    currentSpecDetails.value = [];
  }

  // 清空上一次的选择
  selectedSpecs.value = {};

  // 显示规格选择弹窗
  showSpecModal.value = true;
}

const hideModal = () => {
  showSpecModal.value = false;
  currentSpecGoods.value = {};
  currentSpecDetails.value = [];
};

const handleUpdateCart = (newCart) => {
  // 检查购物车是否有实际变化
  const oldCartJSON = JSON.stringify(cart.value);
  const newCartJSON = JSON.stringify(newCart);

  if (oldCartJSON !== newCartJSON) {
    // 只有购物车内容确实发生变化时，才标记为已更改
    cartHasChanged.value = true;
  }

  cart.value = newCart;
};

const handlePriceUpdate = (newPrice) => {
  cartDisplayPrice.value = newPrice;
};

onMounted(async () => {
  const pages = getCurrentPages();
  const currentPage = pages[pages.length - 1];
  const { id } = currentPage.options;

  if (id) {
    await getMerchantDetails(id);
    await getGoodsList(id);
    await fetchGoodsCategories(id);
    // 在页面基础数据加载完成后，从服务器获取购物车
    await fetchCartFromServer(id);
  }
});

// 从服务器获取并恢复购物车
const fetchCartFromServer = async (merchantId) => {
  const token = uni.getStorageSync("token");
  if (!token) {
    console.log("用户未登录，无需从服务器恢复购物车");
    return;
  }

  try {
    const storedUser = uni.getStorageSync("user");
    if (!storedUser) return;
    const userData = JSON.parse(storedUser);
    const userId = userData.userId;
    if (!userId) return;

    console.log(`正在为用户 ${userId} 在商家 ${merchantId} 获取购物车...`);
    const res = await get(
      `/cart/getGoodFromMySQL?userId=${userId}&merchantId=${merchantId}`
    );

    if (res.data && res.data.code === 200 && res.data.msg) {
      console.log("从服务器获取到购物车数据:", res.data.msg);

      const serverCart = res.data.msg;
      const rehydratedCart = {};

      for (const cartKey in serverCart) {
        const serverItem = serverCart[cartKey];

        // 1. 从已加载的商品列表中查找完整的商品详情
        const goodsDetails = goodsList.value.find(
          (g) => g.id === serverItem.goodId
        );

        if (goodsDetails) {
          // 2. 重新组装成前端组件期望的、包含嵌套 goods 对象的数据结构
          rehydratedCart[cartKey] = {
            goods: goodsDetails,
            quantity: serverItem.goodNum, // 将 goodNum 映射为 quantity
            selectedSpecs: serverItem.specs, // 保留规格信息
            comboInfo: serverItem.comboInfo || null, // 保留套餐信息
            price:
              serverItem.price ||
              (serverItem.comboInfo
                ? serverItem.comboInfo.comPrice
                : goodsDetails.price),
          };
        } else {
          console.warn(
            `购物车恢复失败：在商品列表中未找到ID为 ${serverItem.goodId} 的商品。`
          );
        }
      }

      // 3. 将"再加工"后的完整购物车数据赋值给 ref
      cart.value = rehydratedCart;
      console.log("购物车数据已恢复并格式化:", cart.value);

      // 重置购物车变更标记，因为刚刚从服务器获取的数据
      cartHasChanged.value = false;
    } else {
      console.log("服务器无此购物车数据或获取失败。");
      cart.value = {}; // 清空购物车
      cartHasChanged.value = false; // 重置变更标记
    }
  } catch (error) {
    console.error("从服务器获取购物车失败:", error);
    cart.value = {}; // 出错时也清空，避免数据不一致
    cartHasChanged.value = false; // 重置变更标记
  }
};

// 将购物车数据从Redis同步到数据库
const syncCartToDB = async () => {
  // 首先检查购物车是否有变更
  if (!cartHasChanged.value) {
    console.log("购物车无变更，无需同步到数据库");
    return;
  }

  // 1. 检查用户登录状态
  const token = uni.getStorageSync("token");
  if (!token) {
    console.log("用户未登录，无需同步购物车到数据库");
    return;
  }

  try {
    // 2. 获取用户ID
    const storedUser = uni.getStorageSync("user");
    if (!storedUser) {
      console.error("无法获取到用户信息，同步中止");
      return;
    }
    const userData = JSON.parse(storedUser);
    const userId = userData.userId;

    if (!userId) {
      console.error("无法获取到用户ID，同步中止");
      return;
    }

    // 从 ref 中获取 merchantId
    const merchantId = merchant.value.id;
    if (!merchantId) {
      console.error("无法获取到商家ID，同步中止");
      return;
    }

    console.log(
      `准备将用户 ${userId} 在商家 ${merchantId} 的购物车从Redis同步到数据库...`
    );

    // 计算当前购物车的总价
    const totalPrice = parseFloat(cartDisplayPrice.value);

    // 3. 调用后端接口，传递 userId、merchantId 和 totalPrice
    await post("/cart/addGoodToMySQL", {
      userId,
      merchantId,
      price: totalPrice || 0, // 确保总价为数字，如果解析失败则默认为0
    });
    console.log("购物车到数据库的同步请求已发送，总价：", totalPrice);

    // 同步成功后，重置变更标记
    cartHasChanged.value = false;
  } catch (error) {
    console.error("同步购物车失败:", error);
    // 同步失败时不重置标记，让下次尝试再次同步
  }
};

onUnload(() => {
  // 页面卸载时，只有购物车有变更才执行同步
  console.log("页面卸载，检查是否需要同步购物车");
  syncCartToDB();
});

/*
onHide(() => {
	// 页面隐藏（如切换后台、跳转到其他非tabBar页）时执行同步
	// 根据新需求，已取消此处的同步逻辑
	// console.log('页面隐藏，触发购物车同步');
	// syncCartToDB();
});
*/

async function getMerchantDetails(id) {
  try {
    localStorage.setItem("merchanId", id);
    const allMerchants = uni.getStorageSync("merchants_data") || [];
    const foundMerchant = allMerchants.find((m) => m.id == id);
    if (foundMerchant) {
      merchant.value = foundMerchant;
      deliveryFee.value = foundMerchant.deliveryFee || 0;
      packingFee.value = foundMerchant.packingFee || 0;
    }
  } catch (error) {
    console.error("获取商家详情失败:", error);
  }
}

async function getGoodsList(merchantId) {
  try {
    const res = await get(`/goods/list?merchantId=${merchantId}`);
    goodsList.value = res.data.msg.map((item) => ({
      id: item.good_id,
      name: item.good_name,
      price: item.good_price,
      img: item.good_icon,
      sales: item.sales,
      has_spec: [11, 14].includes(item.good_id),
      typeId: item.good_type_id,
    }));
  } catch (error) {
    console.error("获取商品列表失败:", error);
  }
}

async function fetchGoodsCategories(merchantId) {
  try {
    const res = await get(`/goods/categories?merchantId=${merchantId}`);
    categories.value = [{ id: "all", name: "全部" }, ...res.data.msg];
  } catch (error) {
    console.error("获取商品分类失败:", error);
  }
}

const goToCheckout = async () => {
  if (cartTotal.value === 0) {
    uni.showToast({ title: "购物车还是空的", icon: "none" });
    return;
  }

  uni.showLoading({ title: "正在准备订单..." });
  try {
    // 在去结算前，如果有变更才同步购物车
    if (cartHasChanged.value) {
      await syncCartToDB();
    }

    // 存储购物车数据以供订单确认页使用
    uni.setStorageSync("cart_data", {
      cart: cart.value,
      merchantName: merchant.value.name,
      merchantId: merchant.value.id,
      deliveryFee: deliveryFee.value,
      packingFee: packingFee.value,
    });

    uni.hideLoading();
    uni.navigateTo({ url: "/pages/order/pendingPaymentOrder" });
  } catch (error) {
    uni.hideLoading();
    uni.showToast({ title: "操作失败，请重试", icon: "none" });
    console.error("结算前同步购物车失败:", error);
  }
};
</script>

<style scoped>
.header-card {
  background: #ffffff;
  padding: 30rpx;
  border-radius: 0 0 20rpx 20rpx;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
  margin-bottom: 20rpx;
}

.fixed-nav {
  position: sticky;
  top: 0; /* 根据你的导航栏高度调整 */
  z-index: 1000;
  width: 100%;
}

.content-container {
  margin-top: -90rpx;
  padding-top: 90rpx; /* 为固定Tab留出空间 */
  padding-bottom: 120rpx; /* 为底部结算栏留出空间 */
}

/* 点餐区域美化 */
.order-section {
  /* padding-top: 10rpx; */ /* This padding is no longer needed */
}

.nav-left {
  width: 180rpx;
  background-color: #f8f8f8;
  height: calc(100vh - 100rpx - 120rpx); /* 视口高度 - 顶部Tab - 底部结算栏 */
}
.nav-left .cu-item {
  height: 100rpx;
  line-height: 100rpx;
  text-align: center;
  font-size: 28rpx;
  transition: all 0.2s;
  border-bottom: 1px solid #eee;
}
.nav-left .cu-item.cur {
  background-color: #ffffff;
  color: #e54d42;
  font-weight: bold;
  border-left: 6rpx solid #e54d42;
}

.nav-right {
  background-color: #ffffff;
  flex: 1;
  padding: 0 20rpx;
  height: calc(100vh - 100rpx - 120rpx); /* 同上 */
}
.goods-item {
  display: flex;
  padding: 20rpx 0;
  border-bottom: 1px solid #f2f2f2;
}
.goods-item:last-child {
  border-bottom: none;
}
.goods-img {
  width: 160rpx;
  height: 160rpx;
  border-radius: 10rpx;
  margin-right: 20rpx;
}
.goods-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}
.stepper {
  display: flex;
  align-items: center;
}
.stepper .count {
  padding: 0 16rpx;
  font-size: 30rpx;
}

/* 底部结算栏 */
.shop-foot {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  z-index: 1024;
  box-shadow: 0 -2px 5px rgba(0, 0, 0, 0.1);
  height: 110rpx;
  align-items: center;
}
.shop-foot .submit {
  height: 110rpx;
  line-height: 110rpx;
  width: 220rpx;
  font-size: 32rpx;
}

/* 规格弹窗美化 */
.cu-dialog {
  border-radius: 16rpx;
  overflow: hidden;
}
.spec-section {
  margin-bottom: 20rpx;
}
</style>
